package com.example.module_park.adapter

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.SearchView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.example.lib_common.utils.RouterKey
import com.example.lib_common.utils.RouterPath
import com.example.module_park.R
import com.example.module_park.model.EnterpriseEntity
import com.example.module_park.model.MultiEnterpriseItem

class MultiEnterpriseAdapter(
    private var items: List<MultiEnterpriseItem>
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    // 替代方案1：使用空函数作为默认值
    private var onSearchQueryChange: (String) -> Unit = { } // 默认空lambda

    // 添加更新项目的方法
    fun updateItems(newItems: List<MultiEnterpriseItem>) {
        items = newItems
        notifyDataSetChanged()
    }

    // 添加设置搜索回调的方法
    fun setOnSearchQueryChangeListener(listener: (String) -> Unit) {
        onSearchQueryChange = listener
    }

    companion object {
        private const val TYPE_SEARCH = 0
        private const val TYPE_VERTICAL_LIST = 1
    }

    override fun getItemViewType(position: Int): Int {
        return when (items[position]) {
            is MultiEnterpriseItem.Search -> TYPE_SEARCH
            is MultiEnterpriseItem.VerticalList -> TYPE_VERTICAL_LIST
        }
    }

    override fun getItemCount() = items.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return when (viewType) {
            TYPE_SEARCH -> SearchViewHolder(
                inflater.inflate(R.layout.enterprise_search, parent, false),
                this::onSearchCallback // 传递回调方法
            )
            TYPE_VERTICAL_LIST -> VerticalListViewHolder(
                inflater.inflate(
                    R.layout.enterprise_rv_all,
                    parent,
                    false
                )
            )
            else -> throw IllegalArgumentException("无效视图类型: $viewType")
        }
    }

    // 搜索回调方法（供SearchViewHolder调用）
    private fun onSearchCallback(query: String) {
        onSearchQueryChange(query)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (val item = items[position]) {
            is MultiEnterpriseItem.Search -> (holder as SearchViewHolder).bind(item)
            is MultiEnterpriseItem.VerticalList -> (holder as VerticalListViewHolder).bind(item)
        }
    }

    // 搜索框 ViewHolder（使用构造函数传递适配器的回调方法）
    class SearchViewHolder(
        view: View,
        private val searchCallback: (String) -> Unit // 添加回调参数
    ) : RecyclerView.ViewHolder(view) {
        private val searchLayout: ConstraintLayout = view.findViewById(R.id.search_layout)
        private val searchTextView: TextView = view.findViewById(R.id.tv_search)
        private val searchView: SearchView = view.findViewById(R.id.searchView)

        fun bind(search: MultiEnterpriseItem.Search) {
            searchTextView.text = search.hintText
            val searchText = searchView.findViewById<EditText>(androidx.appcompat.R.id.search_src_text)
            searchText?.hint = search.hintText

            // 点击整个搜索区域激活搜索
            searchLayout.setOnClickListener {
                // 隐藏文本视图，显示搜索视图
                searchTextView.visibility = View.GONE
                searchView.visibility = View.VISIBLE

                // 展开搜索框并请求焦点
                searchView.post {
                    searchView.setIconified(false)
                    searchView.requestFocus()

                    // 弹出键盘
                    val inputMethodManager =
                        itemView.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    inputMethodManager.showSoftInput(
                        searchView.findFocus(),
                        InputMethodManager.SHOW_IMPLICIT
                    )
                }
            }

            // 自定义搜索框样式
            searchView.apply {
                // 设置搜索文本样式
                val searchEditText = this.findViewById<EditText>(androidx.appcompat.R.id.search_src_text)
                searchEditText?.apply {
                    textSize = 14f
                    setTextColor(Color.parseColor("#FF333333"))
                    setHintTextColor(Color.parseColor("#FF999999"))
                }

                // 移除默认的搜索图标
                findViewById<ImageView>(androidx.appcompat.R.id.search_button)?.visibility =
                    View.GONE

                // 设置搜索框监听
                setOnQueryTextListener(object : SearchView.OnQueryTextListener {
                    override fun onQueryTextChange(newText: String?): Boolean {
                        // 调用传递的回调方法
                        searchCallback(newText ?: "")
                        return true
                    }

                    override fun onQueryTextSubmit(query: String?): Boolean {
                        return false
                    }
                })

                // 当搜索框关闭时返回到初始状态
                setOnCloseListener {
                    searchTextView.visibility = View.VISIBLE
                    searchView.visibility = View.GONE
                    false
                }
            }
        }
    }

    // 垂直列表 ViewHolder（直接定义为适配器的内部类）
    inner class VerticalListViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val recyclerView: RecyclerView = view.findViewById(R.id.rv_enterprise_item)

        init {
            recyclerView.layoutManager = LinearLayoutManager(view.context)
            recyclerView.setHasFixedSize(true)
        }

        fun bind(list: MultiEnterpriseItem.VerticalList) {
            recyclerView.adapter = VerticalItemAdapter(list.items)
        }

        private inner class VerticalItemAdapter(
            private val items: List<EnterpriseEntity>
        ) : RecyclerView.Adapter<VerticalItemAdapter.ViewHolder>() {

            inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
                val nameTextView: TextView = view.findViewById(R.id.tv_enterprise_name)
                val typeTextView: TextView = view.findViewById(R.id.tv_type)
                val addressTextView: TextView = view.findViewById(R.id.tv_address)
                val coverTextView: TextView = view.findViewById(R.id.tv_cover)
            }

            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_enterprise_all, parent, false)
            )

            override fun onBindViewHolder(holder: ViewHolder, position: Int) {
                val item = items[position]
                holder.nameTextView.text = item.name
                holder.typeTextView.text =
                    "${item.industryType}"
                holder.addressTextView.text =
                    "${item.address}"
                holder.coverTextView.text =
                    "${item.contactInfo}"
                holder.itemView.setOnClickListener {
                    // 跳转到详情页面
                    ARouter.getInstance().build(RouterPath.ENTERPRISE_DETAIL_UI)
                        .withInt(RouterKey.ENTERPRISE_DETAIL_ID, item.id).navigation()
                }
            }

            override fun getItemCount() = items.size
        }
    }
}